const fs = require("fs");
const request = require('request');
const models = require('../models');
const formidable = require('formidable');//文件上传处理模块
const OSS = require('ali-oss').Wrapper;
const path = require("path");
const MD5 = require('../common/MD5.js');
const UUID = require('uuid');
const time = require("silly-datetime")//时间模块
const Redis = require("../common/redis_db");
const logger = require("../common/logger");
const moment = require('moment');



//引入模型
const Acquiorder = models.acquiorder;//
const Chatrecord = models.chatrecord;//
const Clientuser = models.clientuser;//
const Handling = models.handling;//
const inviteRoom = models.inviteroom;//
const Servicelogin = models.servicelogin;//
const Serviceuser = models.serviceuser;//

//登陆
exports.administer = (req, res) => {
    const usernames = req.body.accountnumber;
    const passwords = MD5(req.body.userpassword);
    if (req.session.user) {
        delete req.session.user;
        res.json({ "success": "ok", "code": 101, "content": "用户已经在线请勿登录！" })
    } else {
        try {
            Serviceuser.findOne({ "username": usernames }, function (err, r) {
                if (err) {
                    return res.json({ "success": "ok", "code": 101, "content": err });
                } else {
                    if (r == null) {
                        return res.json({ "success": "ok", "code": 102, "content": "用户名不存在！" })
                    } else {
                        if ((usernames == r.username) && (passwords == r.userpasswod)) {
                            let pars = {
                                userrole: r.userrole,
                                username: r.username,
                                userid: r.userid,
                                _id: r._id
                            };
                            req.session.user = pars;
                            return res.json({ "success": "ok", "code": 200, "content": pars })

                        } else {
                            return res.json({ "success": "ok", "code": 103, "content": "用户名或者密码错误！" })
                        }
                    }
                }
            });
        } catch (err) {
            return res.json({ "success": "ok", "code": 100, "content": "数据库错误！" })
        };
    }
};
//退出登录
exports.logout = (req, res) => {
    try {
        delete req.session.user;
        res.json({ "success": "ok", "code": 101, "content": "注销成功！" })
    } catch (err) {
        res.json({ "success": "ok", "code": 102, "content": "服务器错误！" })
    }
};

//聊天记录存储
exports.chatrecord = (req, res) => {
    console.log(req.body);
    const {
        roomID,
        username,
        senddate,
        anonymityImg,
        b,
        color,
        headerimg,
        id,
        imggs,
        is,
        msg,
        to,
        type,
    } = req.body;
    if (!roomID || !username) {
        return res.json({
            code: 201,
            mes: '缺少参数'
        })
    };
    Chatrecord.create({
        roomID,
        username,
        senddate: time.format(new Date(), "YYYY-MM-DD HH:mm:ss"),
        anonymityImg,
        b,
        color,
        headerimg,
        id,
        imggs,
        is,
        msg,
        to,
        type,
    }).then(data => {
        if (data) {
            return res.json({
                code: 200,
                content: data,
                mes: '保存成功'
            })
        } else {
            return res.json({
                code: 201,
                mes: '保存失败'
            })
        }
    }).catch(err => {
        console.log(err);
        return res.json({
            code: 201,
            mes: '发生错误'
        })
    })
};
//查看聊天记录
exports.findchat = (req, res) => {
    let {
        roomID,
        username
    } = req.body;
    if (!roomID || !username) {
        return res.json({
            code: 201,
            mes: '缺少参数'
        });
    };
    let limit = Number(req.body.pagesize) || 20;
    let page = Number(req.body.page) || 1;
    if (limit < 1 || limit > 100 || page < 1) {
        return res.send('201');//$lt: {senddate: moment().add(3, 'days') } 
    }
    Chatrecord.find({ roomID: roomID }).sort({ senddate: -1 }).skip((page - 1) * limit).limit(limit).then(data => {
        return res.json({
            code: 200,
            data: data,
            mes: '查询成功'
        })
    }).catch(err => {
        console.log(err);
        return res.json({
            code: 201,
            mes: '发生错误'
        })
    })
};
//医生审核状态
exports.auditResult = (req, res) => {
    console.log(req.body)
    const {
        _id,
        userid
    } = req.body;
    if (!_id) {
        return res.json({
            code: 201,
            mes: '缺少参数'
        })
    };
    Clientuser.findById({ _id, userid }).then(data => {
        return res.json({
            code: 200,
            data: data,
            mes: '查询成功'
        })
    }).catch(err => {
        console.log(err);
        return res.json({
            code: 201,
            mes: '发生错误'
        })
    })
};
//用户问诊记录信息
exports.ask_Record = (req, res) => {
    console.log(req.query)
    const {
        userid,
        page,
        pagesize
    } = req.query;
    if (!userid) {
        return res.json({
            code: 201,
            mes: '缺少参数'
        })
    };
    Clientuser.find({ userid }).limit(parseInt(page)).skip(parseInt(pagesize)).then(data => {
        console.log(data.length)
        return res.json({
            code: 200,
            data: data,
            mes: '查询成功'
        })
    }).catch(err => {
        console.log(err);
        return res.json({
            code: 201,
            mes: '发生错误'
        })
    })
}


//添加用户名
exports.adduser = function (req, res) {
    console.log(req.body)
    let username = "lizhishu";
    let userpasswod = MD5("4561230a");
    let phone = "18942508364";
    let userrole = 1;
    let name = "李智书";
    let addtime = time.format(new Date(), "YYYY-MM-DD HH:mm:ss");
    Serviceuser.create({
        userid: UUID.v4(),
        username: username,
        userpasswod: userpasswod,
        userrole: userrole,
        name: name,
        userimage: null,
        phone: phone,
        date: addtime
    }).then(data => {
        return res.json({
            code: 200,
            msh: "添加成功！"
        })
    }).catch(err => {
        return res.json({
            code: 101,
            msh: "添加失败！"
        })
    });
};


const options = {
    region: 'oss-cn-hangzhou',
    accessKeyId: 'LTAIhhKx9uqhbU3W',
    accessKeySecret: 'DuzQD0dplDRMOxf5dQmO9wErJJQS0z',
    bucket: 'jusexcx'
};
const client = new OSS(options);
client.putBucketCORS('jusexcx', 'oss-cn-hangzhou', [
    {
        allowedOrigin: '*',
        allowedMethod: ['GET', 'POST', 'HEAD', 'PUT', 'DELETE'],
        allowedHeader: ['Content-Type', 'Content-Length', 'Authorization', 'Accept', 'X-Requested-With'],
    }
]);

//小程序发送图片
exports.uploadimg = (req, res) => {
    //跨域请求处理
    // res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Content-Length, Authorization");
    // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // res.header("X-Powered-By", ' 3.2.1');
    // res.header("Content-Type", "application/json;charset=utf-8");
    let form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
        let paths = "";
        if (err) {
            return res.json({
                code: 201,
                mes: '发生错误!'
            })
        }
        let stream = fs.createReadStream(files.files.path);
        if (path.extname(files.files.name) != "") {
            paths = 'Images/' + files.files.name.replace(/(.*)(\..*)/, `${Date.now()}${Math.round(Math.random() * 9)}$2`);
        } else {
            paths = 'Images/' + Date.now() + Math.round(Math.random() * 9) + '.mp3';//pc端音频文件
        }
        client.putStream(paths, stream).then(result => {
            return res.json({
                code: 200,
                mes: '上传成功',
                data: "https://xcximg.juseyun.com/" + result.name
            })
        }).catch(err => {
            console.log(err)
            return res.json({
                code: 201,
                mes: '上传失败!'
            })
        })
    })
};
//查看审核单据
exports.find_documents = (req, res) => {
    const {
        id
    } = req.query;
    if (!id) {
        return res.json({
            code: 201,
            mes: '缺少参数'
        })
    };
    Clientuser.findById({ _id: id }).then(doc => {
        if (!doc) {
            return res.send('202');
        };
        return res.json({
            code: 200,
            content: doc
        });
    }).catch(err => {
        return res.json({
            code: 201,
            content: "发生错误"
        });
    })
};
//医生列表
const serverUser = require('../models/serviceusers');
const Clients = require('../models/clientuser');
exports.onlindoctor = (req, res) => {
    serverUser.count(
        { $or: [{ userRole: 1 }, { userRole: 6 }] }
    ).then(count => {
        return serverUser.find({ $or: [{ userRole: 1 }, { userRole: 6 }] },
            { userPassword: 0, edit: 0, loginState: 0, registDate: 0, loginDate: 0 }).sort({ userRole: -1 }).then(data1 => {
                return Promise.all(data1.map(value => {
                    let query = {
                        $or: [
                            { assTime: null, assistantId: value._id, orderNumber: 1 },
                            { assistantId: value._id, orderNumber: 1, result: 0 },
                            { docTime: null, doctorId: value._id, orderNumber: 2 },
                            { doctorId: value._id, orderNumber: 2, result: 0 }
                        ]
                    }
                    return Clients.count(query).then(count => {
                        value._doc.todo_doctor = count
                        return value
                    })
                })).then(result => {
                    return res.json({
                        success: "OK",
                        code: 200,
                        count,
                        content: result
                    })
                });
            })
    }).catch(err => {
        return res.json({
            success: "OK",
            code: 201,
            text: "发生意外错误"
        })
    })




};
//客服后台管理人员数量
exports.managerdata = (req, res) => {
    serverUser.find({}, function (err, data) {
        if (err) {
            return res.json({
                success: "OK",
                code: 200,
            })
        } else {
            let newarr = [];
            for (let a = 0; a < data.length; a++) {
                data[a].userPassword = null;
                newarr.push(data[a])
            }
            return res.json({
                success: "OK",
                code: 200,
                content: newarr
            })
        }
    })
};


//每个房间用户基本信息缓存
exports.temporary_info = (req, res) => {
    console.log(req.body)
    const {
        roomname,
        content
    } = req.body;
    if (!roomname) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        })
    };
    Redis.select('0', function (error) {
        if (error) {
            logger.info(error)
        } else {
            // set
            Redis.HMSET(roomname, JSON.parse(content), function (error, resdata) {
                if (error) {
                    logger.info(error);
                    return res.json({
                        code: 101,
                        content: error
                    })
                } else {
                    return res.json({
                        success: "OK",
                        code: 200,
                        content: resdata
                    })
                };
                // 关闭链接
                //Redis.end();
            });
        }
    });
};
//每个房间用户基本信息
exports.get_temporary = (req, res) => {
    const {
        roomname
    } = req.body;
    if (!roomname) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        });
    };
    Redis.select('0', function (error) {
        if (error) {
            logger.info(error);
            return res.json({
                success: "OK",
                code: 201
            })
        } else {
            // set
            Redis.HGETALL(roomname, function (error, resdata) {
                if (error) {
                    logger.info(error);
                    return res.json({
                        success: "OK",
                        code: 201
                    })
                } else {
                    if (resdata) {
                        return res.json({
                            success: "OK",
                            code: 200,
                            content: resdata
                        })
                    } else {
                        return res.json({
                            success: "OK",
                            code: 201,
                            content: null
                        })
                    }

                };
                // 关闭链接
                Redis.end();
            });
        }
    });
};
//修改缓存数据
exports.modification = (req, res) => {
    const {
        roomname,
        state
    } = req.body;
    if (!roomname || !state) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        });
    };
    Redis.select('0', function (error) {
        if (error) {
            logger.info(error);
            return res.json({
                success: "OK",
                code: 201
            })
        } else {
            // set
            Redis.HMSET(roomname, { state: state }, function (error, resdata) {
                if (error) {
                    logger.info(error);
                    return res.json({
                        success: "OK",
                        code: 201
                    })
                } else {
                    if (resdata) {
                        return res.json({
                            success: "OK",
                            code: 200,
                            content: resdata
                        })
                    } else {
                        return res.json({
                            success: "OK",
                            code: 201,
                            content: null
                        })
                    };
                };
                //关闭链接
                Redis.end();
            });
        }
    });
};
//结束服务删除数据
exports.del_temporary = (req, res) => {
    const {
        roomname
    } = req.body;
    if (!roomname) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        });
    };
    Redis.select('0', function (error) {
        if (error) {
            logger.info(error);
            return res.json({
                success: "OK",
                code: 201
            })
        } else {
            // set
            Redis.DEL(roomname, function (error, resdata) {
                if (error) {
                    logger.info(error);
                    return res.json({
                        success: "OK",
                        code: 201
                    })
                } else {
                    if (resdata) {
                        return res.json({
                            success: "OK",
                            code: 200,
                            content: resdata
                        })
                    } else {
                        return res.json({
                            success: "OK",
                            code: 201,
                            content: null
                        })
                    };
                };
                // 关闭链接
                Redis.end();
            });
        }
    });
};
//邀请列表inviteroom
exports.inviteroom = (req, res) => {
    const {
        id,
        roomID,
        time,
        state,
        username,
        socket_id,
        roomname
    } = req.body;
    if (!id || !roomID || !state || !socket_id) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        })
    };
    inviteRoom.create({
        name: id,
        socket_id: socket_id,
        uuid: UUID.v4(),
        roomID: roomID,
        username: username,
        results: state,
        time: time,
        roomname: roomname
    }).then(datas => {
        return res.json({
            msg: "保存成功",
            code: 200,
        })
    }).catch(err => {
        return res.json({
            msg: "保存失败",
            code: 201,
        })
    })
};
//查询邀请列表inviteroom
exports.findinviteroom = (req, res) => {
    const {
        id
    } = req.body;
    if (!id) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        })
    };
    const limit = parseInt(req.body.limit) || 10;
    const page = parseInt(req.body.page) || 1;
    inviteRoom.count({
        name: id
    }).then(count => {
        return inviteRoom.find({
            name: id
        }).sort({ time: -1 }).limit(limit).skip((page - 1) * limit).then(datas => {
            return res.json({
                msg: "查询成功",
                code: 200,
                content: datas,
                count
            })
        })
    }).catch(err => {
        console.log(err)
        return res.json({
            code: 201,
            mes: '发生错误'
        })
    })
};

//ficationinvite  修改邀请信息状态
exports.ficationinvite = (req, res) => {
    console.log(req.body)
    const {
        id,
        _id,
        state
    } = req.body;
    if (!id || !_id) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        })
    };
    inviteRoom.update(
        {
            _id: { $in: _id }
        }, {
            $set: {
                results: state
            }
        }
    ).then(data => {
        return res.json({
            code: 200,
            success: data,
        })
    }).catch(err => {
        console.log(err);
        return res.json({
            code: 201,
            mes: '发生错误'
        })
    })
};
//医生、助理加入房间信息
exports.doctor_Roominfo = (req, res) => {
    const {
        userid,
        roomID
    } = req.body;
    if (!userid || !roomID) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        });
    };
    Redis.select('1', function (error) {
        if (error) {
            logger.info(error);
            return res.json({
                success: "OK",
                code: 201
            })
        } else {
            // set
            Redis.SADD(userid, JSON.stringify(roomID), function (error, resdata) {
                if (error) {
                    logger.info(error);
                    return res.json({
                        success: "OK",
                        code: 201
                    })
                } else {
                    return res.json({
                        success: "OK",
                        code: 200,
                        content: resdata
                    })
                };
                // 关闭链接
                Redis.end();
            });
        }
    });
};

//查询医生加入房间信息
exports.find_Roominfo = (req, res) => {
    const {
        userid
    } = req.body;
    if (!userid) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        });
    };
    Redis.select('1', function (error) {
        if (error) {
            logger.info(error);
            return res.json({
                success: "OK",
                code: 201
            })
        } else {
            // set
            Redis.smembers(userid, function (error, resdata) {
                if (error) {
                    logger.info(error);
                    return res.json({
                        success: "OK",
                        code: 201
                    })
                } else {
                    let newarr=[];
                    resdata.map(value=>{
                        newarr.push(JSON.parse(JSON.parse(value)));
                    })
                    if (resdata.length>0) {
                        return res.json({
                            success: "OK",
                            code: 200,
                            content: newarr
                        })
                    } else {
                        return res.json({
                            success: "OK",
                            code: 201,
                            content: []
                        })
                    }
                };
                // 关闭链接
                Redis.end();
            });
        }
    });
};
//删除医生加入房间信息
exports.lrem_Roominfo = (req, res) => {
    const {
        userid,
        roomID
    } = req.body;
    if (!userid) {
        return res.json({
            msg: "缺少必要参数",
            code: 201,
        });
    };
    Redis.select('1', function (error) {
        if (error) {
            logger.info(error);
            return res.json({
                success: "OK",
                code: 201
            })
        } else {
            // set
            Redis.SREM(userid, 0, JSON.stringify(roomID), function (error, resdata) {
                if (error) {
                    logger.info(error);
                    return res.json({
                        success: "OK",
                        code: 201
                    })
                } else {
                    if (resdata) {
                        return res.json({
                            success: "OK",
                            code: 200,
                            content: resdata
                        })
                    } else {
                        return res.json({
                            success: "OK",
                            code: 201,
                            content: null
                        })
                    }
                };
                // 关闭链接
                Redis.end();
            });
        }
    });
};
//





